package com.jsaas.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jsaas.model.Permission;
import com.jsaas.sys.service.PermissionService;
import com.jsaas.utils.MyUtils;
import com.jsaas.utils.ShiroUtils;

/**   
* @Title: AuthorityInterceptor.java 
* @Package com.jsaas.interceptor 
* @Description: TODO(系统功能权限权限验证拦截器 动态url权限验证) 
* @author tuozq 
* @date 2017年12月15日 下午2:02:36 
* @version V1.0   
*/
public class AuthorityInterceptor implements Interceptor {

	public void intercept(Invocation inv) {
		// TODO Auto-generated method stub
		if(ShiroUtils.isLogin()){
			//验权
			Controller controller = inv.getController();
			String actionKey = inv.getActionKey();
			HttpServletRequest request = controller.getRequest();
			//获取系统中已启用的功能权限
			Map<String, Permission> allPermissions = PermissionService.getAllEnablePermission();
			//actionkey 中添加 permission 字段，ShiroDbRealm doGetAuthorizationInfo方法中构建 permission 到 SimpleAuthorizationInfo.addStringPermissions
			//通过 SecurityUtils.getSubject().isPermitted(permission); 验证是否有actionkey对应的权限
			
			if(allPermissions.containsKey(actionKey)){//是否有维护actionkey对应的权限 并且已启用
				Permission perm = allPermissions.get(actionKey);
				if(StrKit.notBlank(perm.getPermission())){
					if(!SecurityUtils.getSubject().isPermitted(perm.getPermission())){//验证用户是否拥有权限
						boolean isAjax = MyUtils.isAjax(request);
						if(isAjax){
							controller.renderJson(Ret.fail().set("msg", "权限不足，对不起，您没有 "+ actionKey +" 的操作权限。"));
						}else{
							String redirctUrl = request.getHeader("referer");
							if (StringUtils.isBlank(redirctUrl)) {
								redirctUrl = request.getRequestURI();
							}
							controller.setAttr("actionkey", actionKey);
							controller.setAttr("redirctUrl", redirctUrl);
							controller.render("/views/error/403.html");
						}
						return;
					}
				}
				
			}
		}
		inv.invoke();
	}

}
